package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jyt.message.Message;
import com.jyt.message.MessageConfig;
import com.jyt.util.MySerializable;

import org.json.JSONObject;

import java.util.List;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.GloableParams;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.ChatManager;
import wetalk.software.bupt.com.wetalk.application.CustomApplication;
import wetalk.software.bupt.com.wetalk.application.MessageReceiver;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.application.WeTalkInvitation;
import wetalk.software.bupt.com.wetalk.application.WeTalkNotifyManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClient;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.EventListener;
import wetalk.software.bupt.com.wetalk.model.po.ChatUser;
import wetalk.software.bupt.com.wetalk.model.po.Group;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkMsg;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.view.dialog.TitleMenu.ActionItem;
import wetalk.software.bupt.com.wetalk.view.dialog.TitleMenu.TitlePopup;
import wetalk.software.bupt.com.wetalk.view.fragment.Fragment_Friends;
import wetalk.software.bupt.com.wetalk.view.fragment.Fragment_Msg;
import wetalk.software.bupt.com.wetalk.view.fragment.Fragment_Profile;


public class MainActivity extends BaseActivity implements EventListener {
    private TextView txt_title;
    private RelativeLayout rvImgRight;//右上角加号布局,可设置可见性
    private RelativeLayout searchImgRight;//右上角搜索符号布局
    private TextView unreaMsgdLabel;// 未读消息textview
    private TextView unreadAddressLable;// 未读通讯录textview
    private Fragment[] fragments;
    public Fragment_Msg homefragment;
    private Fragment_Friends contactlistfragment;
    private Fragment_Profile profilefragment;
    private ImageView[] imagebuttons;
    private TextView[] textviews;
    private int currentIndex,index;
    TitlePopup titlePopup;
    ImageView iv_recent_tips,iv_contact_tips;//消息提示
    private SharedPreferences.Editor editor;

    private static final String TAG="XIAOMA?MainActivity";


    private AndroidClientService service=new AndroidClientService();
    private AndroidClientService.SendBinder sendBinder=(AndroidClientService.SendBinder) service.onBind(new Intent());


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG,"onCreate执行了");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //开启service
        Intent startIntent = new Intent(this, AndroidClientService.class);
        String userID= UserManager.getInstance(this).getCurrentUserObjectId();
        startIntent.putExtra("userID",userID);
        startService(startIntent);

        initDataBase();
        initGroup();
        initTitle();
        initTabView();
        initPopWindow();
        //开启广播接收器
        initNewMessageBroadCast();
        initTagMessageBroadCast();
        updateUnreadLabel();
    }




    public void sendPullUser(){
        final String userId= UserManager.getInstance(MainActivity.this).getCurrentUser().getUserID();
        final String targetId = "sys_friend";
        final JSONObject json=new JSONObject();
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"pullUser",bs);

                AndroidClient androidClient=new AndroidClient(GloableParams.ip, MessageConfig.server_name,userId,MainActivity.this);
                androidClient.work();
                androidClient.send(msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();
    }

    public void sendPullGroup(){
        final String userId= UserManager.getInstance(MainActivity.this).getCurrentUser().getUserID();
        final String targetId = "sys_group";
        final JSONObject json=new JSONObject();
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"pullGroup",bs);

                AndroidClient androidClient=new AndroidClient(GloableParams.ip, MessageConfig.server_name,userId,MainActivity.this);
                androidClient.work();
                androidClient.send(msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();
    }



    private void initDataBase(){
        if(isNewUser()){
            sendPullUser();
        }
    }

    private Boolean isNewUser(){
        List<ChatUser> list=WeTalkDB.create(MainActivity.this).getUserList();
        return list.size() == 0;
    }

    private void initGroup() {
        //应该从服务端获取
        WeTalkDB.create(MainActivity.this).deleteAllGroup();
        sendPullGroup();
    }

    private Boolean hasGroupData(){
        List<Group> groupList=WeTalkDB.create(this).queryGroupList();
        if(groupList==null){
            return false;
        } else{
            return true;
        }
    }

    private void initTitle(){
        txt_title = (TextView) findViewById(R.id.txt_title);
        rvImgRight=(RelativeLayout) findViewById(R.id.rv_img_right);
        rvImgRight.setVisibility(View.VISIBLE);
        searchImgRight = (RelativeLayout) findViewById((R.id.rv_searchImg_right));
        searchImgRight.setVisibility(View.VISIBLE);
        searchImgRight.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,searchActivity.class);
                startActivity(intent);
            }
        });
        txt_title.setText("会话");
        rvImgRight.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                titlePopup.show(findViewById(R.id.layout_bar));
            }
        });
    }

    private void initTabView() {
        unreaMsgdLabel = (TextView) findViewById(R.id.unread_msg_number);
        unreadAddressLable = (TextView) findViewById(R.id.unread_address_number);
        homefragment = new Fragment_Msg();
        contactlistfragment = new Fragment_Friends();
        profilefragment = new Fragment_Profile();
        fragments = new Fragment[] { homefragment, contactlistfragment, profilefragment };
        imagebuttons = new ImageView[3];
        imagebuttons[0] = (ImageView) findViewById(R.id.ib_weixin);
        imagebuttons[1] = (ImageView) findViewById(R.id.ib_contact_list);
        imagebuttons[2] = (ImageView) findViewById(R.id.ib_profile);

        imagebuttons[0].setSelected(true);
        textviews = new TextView[3];
        textviews[0] = (TextView) findViewById(R.id.tv_weixin);
        textviews[1] = (TextView) findViewById(R.id.tv_contact_list);
        textviews[2] = (TextView) findViewById(R.id.tv_profile);
        textviews[0].setTextColor(0xFF489cfa);
        // 添加显示第一个fragment
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, homefragment)
                .add(R.id.fragment_container, contactlistfragment)
                .add(R.id.fragment_container, profilefragment)
                .hide(contactlistfragment).hide(profilefragment)
                .show(homefragment).commit();
        currentIndex=0;
    }

    public void onTabClicked(View view){
        switch (view.getId()){

            case R.id.re_weixin:
                index=0;
                txt_title.setText("会话");
                rvImgRight.setVisibility(View.VISIBLE);
                searchImgRight.setVisibility(View.VISIBLE);

                break;

            case R.id.re_contact_list:
                index=1;
                txt_title.setText("通讯录");
                rvImgRight.setVisibility(View.VISIBLE);
                searchImgRight.setVisibility(View.INVISIBLE);

                break;

            case R.id.re_profile:
                index=2;
                txt_title.setText("我");
                rvImgRight.setVisibility(View.GONE);
                searchImgRight.setVisibility(View.INVISIBLE);
                break;
        }
        if(currentIndex!=index){
            FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
            ft.hide(fragments[currentIndex]);
            if(!fragments[index].isAdded()){
                ft.add(R.id.fragment_container,fragments[index]);
            }
            ft.show(fragments[index]).commit();
            imagebuttons[currentIndex].setSelected(false);
            imagebuttons[index].setSelected(true);
            textviews[currentIndex].setTextColor(0xFF999999);
            textviews[index].setTextColor(0xFF489cfa);
            currentIndex=index;
        }

    }

    private void initPopWindow() {
        // 实例化标题栏弹窗
        titlePopup = new TitlePopup(this, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        titlePopup.setItemOnClickListener(onitemClick);

        // 给标题栏弹窗添加子类
        titlePopup.addAction(new ActionItem(this, R.string.menu_groupchat,
                R.drawable.icon_menu_group));
        titlePopup.addAction(new ActionItem(this, R.string.menu_addfriend,
                R.drawable.icon_menu_addfriend));
//        titlePopup.addAction(new ActionItem(this,"部门信息",R.drawable.icon_department));
    }

    private TitlePopup.OnItemOnClickListener onitemClick = new TitlePopup.OnItemOnClickListener() {

        @Override
        public void onItemClick(ActionItem item, int position) {
            // mLoadingDialog.show();
            switch (position) {
                case 0:// 发起群聊
                    Intent intent=new Intent(MainActivity.this, AddGroupChatActivity.class);//// TODO: 2017/12/23  
                    startActivity(intent);

                    break;
                case 1:// 添加朋友
                    Intent intent1=new Intent(MainActivity.this,AddFriendsActivity.class);
                    startActivity(intent1);

                    break;
                default:
                    break;
            }

        }
    };

    /**
     * 获取未读消息数
     */
    public void updateUnreadLabel() {

       //int count = ChatManager.getInstance().getUnreadMsgsCount();
        //int count = WeTalkDB.create(mcontext).getAllUnReadCount();
        int count =0;
        if (count > 0) {
            unreaMsgdLabel.setText(String.valueOf(count));
            unreaMsgdLabel.setVisibility(View.VISIBLE);
        } else {
            unreaMsgdLabel.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MessageReceiver.ehList.add(MainActivity.this);// 监听推送的消息
        //清空
        MessageReceiver.mNewNum=0;
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MessageReceiver.ehList.remove(this);// 取消监听推送的消息
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(userReceiver);
        unregisterReceiver(newReceiver);
        ChatManager.getInstance(this).unBindService();
        UserManager.getInstance(this).unBindService();

    }

    @Override
    public void onMessage(WeTalkMsg message) {
        // TODO Auto-generated method stub
        refreshNewMsg(message);
    }


    /** 刷新界面
     * @Title: refreshNewMsg
     * @Description: TODO
     * @param @param message
     * @return void
     * @throws
     */
    private void refreshNewMsg(WeTalkMsg message){
        // 声音提示
        /*boolean isAllow = CustomApplication.getInstance().getSpUtil().isAllowVoice();
        if(isAllow){
            CustomApplication.getInstance().getMediaPlayer().start();
        }
        iv_recent_tips.setVisibility(View.VISIBLE);*/

        //也要存储起来
        if(message!=null){
            ChatManager.getInstance(MainActivity.this).saveReceiveMessage(true,message);
        }
        if(currentIndex==0){
            //当前页面如果为会话页面，刷新此页面
            if(homefragment != null){
                homefragment.refresh();
            }
        }
    }

    NewBroadcastReceiver  newReceiver;

    private void initNewMessageBroadCast(){
        // 注册接收消息广播
        newReceiver = new NewBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(WeTalkConfig.BROADCAST_NEW_MESSAGE);
        //优先级要低于ChatActivity
        intentFilter.setPriority(3);
        registerReceiver(newReceiver, intentFilter);
    }

    /**
     * 新消息广播接收者
     *
     */
    private class NewBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //刷新界面
            refreshNewMsg(null);
            // 记得把广播给终结掉
            abortBroadcast();
        }
    }

    TagBroadcastReceiver  userReceiver;

    private void initTagMessageBroadCast(){
        // 注册接收消息广播
        userReceiver = new TagBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(WeTalkConfig.BROADCAST_ADD_USER_MESSAGE);
        //优先级要低于ChatActivity
        intentFilter.setPriority(3);
        registerReceiver(userReceiver, intentFilter);
    }

    /**
     * 标签消息广播接收者
     */
    private class TagBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            WeTalkInvitation message = (WeTalkInvitation) intent.getSerializableExtra("invite");
            refreshInvite(message);
            // 记得把广播给终结掉
            abortBroadcast();
        }
    }

    /** 刷新好友请求
     * @Title: notifyAddUser
     * @Description: TODO
     * @param @param message
     * @return void
     * @throws
     */
    private void refreshInvite(WeTalkInvitation message){
        boolean isAllow = CustomApplication.getInstance().getSpUtil().isAllowVoice();
        if(isAllow){
            CustomApplication.getInstance().getMediaPlayer().start();
        }
        iv_contact_tips.setVisibility(View.VISIBLE);
        if(currentIndex==1){
            if(contactlistfragment != null){
                //这个fragment没有设置refresh
                // contactlistfragment.refresh();
            }
        }else{
            //同时提醒通知
            String tickerText = message.getFromname()+"请求添加好友";
            boolean isAllowVibrate = CustomApplication.getInstance().getSpUtil().isAllowVibrate();
            WeTalkNotifyManager.getInstance(this).showNotify(isAllow,isAllowVibrate,R.drawable.ic_launcher, tickerText, message.getFromname(), tickerText.toString(),NewFriendsActivity.class);
        }
    }

    @Override
    public void onNetChange(boolean var1) {

    }

    @Override
    public void onAddUser(WeTalkInvitation var1) {

    }

    @Override
    public void onOffline() {

    }
}
